package com.gitee.wsl.android.ext.base

import android.text.format.Formatter
import com.gitee.wsl.android.ext.ApplicationInit.application
import com.gitee.wsl.android.ext.device.clipboardString
import com.gitee.wsl.ext.string.EMPTY
import com.github.promeg.pinyinhelper.Pinyin
import timber.log.Timber
import java.net.MalformedURLException
import java.net.URL
import java.text.Normalizer
import java.util.Locale
import java.util.regex.Pattern

fun Long.toFileSizeString(): String =
    Formatter.formatFileSize(application, this)

fun Long.toShortFileSizeString(): String =
    Formatter.formatShortFileSize(application, this)

fun String.toURLorNull(): URL? {
    try{
        return URL(clipboardString)
    }catch (e: MalformedURLException) {
        Timber.d("Clipboard does not contain a valid URL: ${com.gitee.wsl.android.ext.device.clipboardString}")
    }
    return null
}


/**
 * Normalize a string to lowercase string
 * This is used for substring matching.
 * Characters must be normalized independently so that
 * A.contains(B) -> A.normalize().contains(B.normalize()) is true.
 */
fun String.normalize(): String {
    return stripAccents(this.romanize().lowercase(Locale.getDefault()))
        .replace("æ", "ae")
        .replace("œ", "oe")
        .replace("ß", "ss")
}

/**
 * Romanize a string, transliterate non-latin characters into latin
 * This is used for sorting. The resulting string represents the position where the original
 * string should be sorted in the latin alphabet.
 */
fun String.romanize(): String {
    return Pinyin.toPinyin(this, "")
}

/**
 *
 * Removes diacritics (~= accents) from a string. The case will not be altered.
 *
 * For instance, '' will be replaced by 'a'.
 *
 * Note that ligatures will be left as is.
 *
 * <pre>
 * StringUtils.stripAccents(null)                = null
 * StringUtils.stripAccents("")                  = ""
 * StringUtils.stripAccents("control")           = "control"
 * StringUtils.stripAccents("clair")     = "eclair"
</pre> *
 *
 * @param input String to be stripped
 * @return input text with diacritics removed
 *
 * @since 3.0
 */
// See also Lucene's ASCIIFoldingFilter (Lucene 2.9) that replaces accented characters by their unaccented equivalent (and uncommitted bug fix: https://issues.apache.org/jira/browse/LUCENE-1343?focusedCommentId=12858907&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_12858907).
fun stripAccents(input: String): String {
    val decomposed = StringBuilder(Normalizer.normalize(input, Normalizer.Form.NFD))
    convertRemainingAccentCharacters(decomposed)
    // Note that this doesn't correctly remove ligatures...
    return STRIP_ACCENTS_PATTERN.matcher(decomposed).replaceAll(String.EMPTY)
}

/**
 * Pattern used in [.stripAccents].
 */
private val STRIP_ACCENTS_PATTERN = Pattern.compile("\\p{InCombiningDiacriticalMarks}+") //$NON-NLS-1$


private fun convertRemainingAccentCharacters(decomposed: StringBuilder) {
    for (i in decomposed.indices) {
        if (decomposed[i] == '\u0141') {
            decomposed.setCharAt(i, 'L')
        } else if (decomposed[i] == '\u0142') {
            decomposed.setCharAt(i, 'l')
        }
    }
}